package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


/**
 * @author ZJG
 * @date 2020-03-07 11:38
 */

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Address> list = addressDao.findByCondition(queryString);
        return new PageResult(list.getTotal(), list.getResult());
    }

    @Override
    public Boolean delete(Integer id) {
        int i = addressDao.findAddressAndOrderById(id);
        if (i == 0) {//说明没有用户预约此体检机构，可以删除
            try {
                addressDao.deleteAddress(id);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    @Override
    public Boolean Add(Address address) {
        if (address.getAddress()==null){
            return false;
        }
        String organization = address.getOrganization();
        Address add = addressDao.findAddress(organization);
        //同一个体检机构名  查出来 地址一样说明是同一家
        if (add == null || (!add.getAddress().equals(address.getAddress()))) {
            addressDao.Add(address);
            return true;
        }
        return false;
    }

    @Override
    public Address findAddressById(int id) {
        return addressDao.findAddressById(id);
    }

    @Override
    public void edit(Address address) {
        String organization = address.getOrganization();
        Address add = addressDao.findAddress(organization);
        if (!(add.getAddress().equals(address.getAddress()) && add.getImg().equals(address.getImg()) && add.getLatitude().equals(address.getLatitude()) && add.getLongitude().equals(address.getLongitude()) && add.getTelephone().equals(address.getTelephone()))) {
            addressDao.edit(address);
        }
    }
}
